package com.simon.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simon.train.business.domain.TrainCarriage;
import com.simon.train.business.domain.TrainCarriageExample;
import com.simon.train.business.dto.TrainCarriageQueryDto;
import com.simon.train.business.dto.TrainCarriageSaveDto;
import com.simon.train.business.enums.SeatColEnum;
import com.simon.train.business.mapper.DailyTrainCarriageMapper;
import com.simon.train.business.mapper.TrainCarriageMapper;
import com.simon.train.business.vo.TrainCarriageQueryVO;
import com.simon.train.common.exception.BusinessException;
import com.simon.train.common.exception.BusinessExceptionEnum;
import com.simon.train.common.util.SnowUtil;
import com.simon.train.common.vo.PageVO;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TrainCarriageService {

    private static final Logger LOG = LoggerFactory.getLogger(TrainCarriageService.class);

    @Resource
    private TrainCarriageMapper trainCarriageMapper;

    @Resource
    private DailyTrainCarriageMapper dailyTrainCarriageMapper;

    public void SaveTrainCarriage(TrainCarriageSaveDto trainCarriageSaveDto){

        /**
         * 自动计算列数和座位总数
         * 不需要前端去计算 前端只需要传入行数即可
         */
        List<SeatColEnum> colsByType = SeatColEnum.getColsByType(trainCarriageSaveDto.getSeatType());
        trainCarriageSaveDto.setColCount(colsByType.size());
        trainCarriageSaveDto.setSeatCount(trainCarriageSaveDto.getColCount() * trainCarriageSaveDto.getRowCount());

        TrainCarriage trainCarriage = BeanUtil.copyProperties(trainCarriageSaveDto, TrainCarriage.class);
        if (ObjectUtil.isNull(trainCarriage.getId())){
            //对于首次保存 也就是新增 需要对字段单独做处理
            TrainCarriage stationDB = SelectByUnique(trainCarriageSaveDto.getTrainCode(),
                    trainCarriageSaveDto.getIndex());

            if(ObjectUtil.isNotEmpty(stationDB)){
                throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_CARRIAGE_INDEX_UNIQUE_ERROR);
            }

            trainCarriage.setId(SnowUtil.getSnowflakeNextId());
            DateTime time = DateTime.now();
            trainCarriage.setCreateTime(time);
            trainCarriage.setUpdateTime(time);
            trainCarriageMapper.insert(trainCarriage);
        } else {
            trainCarriage.setUpdateTime(DateTime.now());
            trainCarriageMapper.updateByPrimaryKey(trainCarriage);
        }

    }

    /**
     * 将这个通过查询唯一键是否为空的方法给提取出来
     * 便于后续针对所有的唯一键的查询进行调用
     * @param
     * @return
     */
    private TrainCarriage SelectByUnique(String trainCode, Integer index) {
        TrainCarriageExample trainCarriageExample = new TrainCarriageExample();
        trainCarriageExample.createCriteria()
                .andTrainCodeEqualTo(trainCode)
                .andIndexEqualTo(index);
        List<TrainCarriage> list = trainCarriageMapper.selectByExample(trainCarriageExample);
        if(CollUtil.isNotEmpty(list)){
            return list.get(0);
        }else return null;
    }

    public PageVO<TrainCarriageQueryVO> QueryTrainCarriageList(TrainCarriageQueryDto trainCarriageQueryDto){
        TrainCarriageExample trainCarriageExample = new TrainCarriageExample();
        trainCarriageExample.setOrderByClause("train_code asc, `index` asc");
        TrainCarriageExample.Criteria criteria = trainCarriageExample.createCriteria();

        if(ObjectUtil.isNotEmpty(trainCarriageQueryDto.getTrainCode())){
            criteria.andTrainCodeEqualTo(trainCarriageQueryDto.getTrainCode());
        }

        LOG.info("当前请求的页码：{}", trainCarriageQueryDto.getPage());
        LOG.info("每页条数：{}", trainCarriageQueryDto.getPageSize());

        PageHelper.startPage(trainCarriageQueryDto.getPage(),trainCarriageQueryDto.getPageSize());
        List<TrainCarriage> trainCarriageList = trainCarriageMapper.selectByExample(trainCarriageExample);

        PageInfo<TrainCarriage> pageInfo = new PageInfo<>(trainCarriageList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<TrainCarriageQueryVO> lists = BeanUtil.copyToList(trainCarriageList, TrainCarriageQueryVO.class);
        PageVO<TrainCarriageQueryVO> pageVO = new PageVO<>();
        pageVO.setList(lists);
        pageVO.setTotal(pageInfo.getTotal());

        return pageVO;
    }

    public void deleteTrainCarriage(Long id) {
        trainCarriageMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据列车的编号直接查询其对应的所有列车车厢情况
     * @param trainCode
     * @return
     */
    public List<TrainCarriage> QueryAllCarriageByTrainCode(String trainCode){
        TrainCarriageExample trainCarriageExample = new TrainCarriageExample();
        trainCarriageExample.setOrderByClause("`index` asc");
        TrainCarriageExample.Criteria criteria = trainCarriageExample.createCriteria();
        criteria.andTrainCodeEqualTo(trainCode);
        return trainCarriageMapper.selectByExample(trainCarriageExample);
    }

    public List<TrainCarriage> SelectByTrainCode(String trainCode) {
        TrainCarriageExample trainCarriageExample = new TrainCarriageExample();
        trainCarriageExample.setOrderByClause("`index` asc");
        trainCarriageExample.createCriteria().andTrainCodeEqualTo(trainCode);
        /**
         * Mybatis默认查询结果为空时 会返回空 而不是空指针 从而不会出现空指针异常
         */
        return trainCarriageMapper.selectByExample(trainCarriageExample);
    }
}
